package com.zl.quickdoc.resolver;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration;
import com.zl.quickdoc.framework.IApiFramework;
import com.zl.quickdoc.model.ApiModule;
import com.zl.quickdoc.utils.ParserJavaUtils;

/**
 * java代码内容解析
 *
 * @author zhouliang
 *
 */
public class JavaUnitParserFactory {
    
    public static List<ApiModule> resolve(String javaPath,String classPath, IApiFramework framework) throws Exception{
        JavaSourceFileFactory ist = JavaSourceFileFactory.getInstance();
        Map<String, CompilationUnit> javaUnitMap = ist.buildJava(javaPath);
        ist.buildClass(classPath);
        
        List<ApiModule> apiModules = new LinkedList<>();
        if(javaUnitMap.isEmpty()){
            System.out.println("【JavaUnitParser】未解析到java文件，请检查目录");
            return apiModules;
        }
        
        for (Entry<String, CompilationUnit> javaUnit:javaUnitMap.entrySet()) {
            String classname = javaUnit.getKey();
            CompilationUnit cu = javaUnit.getValue();
            try {
                ClassOrInterfaceDeclaration classOrInterface = cu.getType(0).asClassOrInterfaceDeclaration();
                if(classOrInterface.isInterface() || !framework.matched(classname)) {
                    continue;
                }
                List<CompilationUnit> fatherList = ist.getSelfFatherInterface(classname);
                if (!framework.support(fatherList)) {
                    continue;
                }
                ApiModule apiModule = ParserJavaUtils.analysisApiModule(fatherList, ist, framework);
                if(apiModule != null) {
                    apiModules.add(apiModule);
                }
            } catch (Exception e) {
                System.out.println("【JavaUnitParser】解析失败:"+ classname+", "+ e.getMessage());
            }
        }
        
        return framework.extend(apiModules);
    }

}
